﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;

namespace FindMe
{
    public partial class Settings : PhoneApplicationPage
    {

        bool validOldPassword = false;
        bool validPassword = false;
        bool validPassword2 = false;
        bool UserImageChanged = false;
        bool UserHomeLocationChanged = false;
        public BitmapImage newUserImage = null;
// Create a filename for JPEG file in isolated storage.
            String userJPEG = "userImage.jpg";
            public string oldUserHomeLocation = null;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;


        public Settings()
        {
            InitializeComponent();
            anyNews();
            //Says hello to the user
            this.txbHiSettings.Text = "Hi "+ App.FullName.ToString() + "!";
            
            //Saves old user image
            if (App.OldUserImage != null)
            {
                this.imgNewUserPicture.Source = App.OldUserImage;
            }

            //If there's a saved UserHomeLocation it will center the map to that Location.
            ///<! --- Home Location pin
            if (App.UserHomeLocation != string.Empty)
            {
                oldUserHomeLocation = App.UserHomeLocation;
                //App.UserHomeLocation Lat and Long separation
                string strFull = App.UserHomeLocation;
                char[] strSeparator = new char[] { ',' };   // <-- Split on these
                string[] strFullArray = strFull.Split(strSeparator, StringSplitOptions.RemoveEmptyEntries);
                string strLat = string.Empty;
                string strLon = string.Empty;
                foreach (string entry in strFullArray)
                {
                    if (strLat == string.Empty)
                    {
                        strLat = entry;
                    }
                    else
                    {
                        strLon = entry;
                    }
                }
                //Adding the pin with the separated coordinates now
                Pushpin pinHome = new Pushpin();
                pinHome.Location = new GeoCoordinate(Convert.ToDouble(strLat), Convert.ToDouble(strLon));//< -- Using separated strings here :D
                map.Center = new GeoCoordinate(Convert.ToDouble(strLat), Convert.ToDouble(strLon));
                map.ZoomLevel = 15;
                map.Children.Add(pinHome);

                // Content of pin
                pinHome.Content = "Home";

            }
          }

        private void btnHome_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
             NavigationService.Navigate(new Uri(App.PathMain,UriKind.Relative));
        }

        private void btnInbox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathConversations, UriKind.Relative));
        }

        private void btnRequests_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathNotifications, UriKind.Relative));
        }

       

        private void anyNews()
        {
            if (App.counterInbox <= 0)
            {
                borderInbox.Visibility = Visibility.Collapsed;
            }
            else
            {
                borderInbox.Visibility = Visibility.Visible;
                countInbox.Text = App.counterInbox.ToString();
            }
            if (App.counterRequest == 0)
            {
                borderRequest.Visibility = Visibility.Collapsed;
            }
            else
            {
                borderRequest.Visibility = Visibility.Visible;
                countRequest.Text = App.counterRequest.ToString();
            }
        }

        private void txtPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            if (txtPassword.Password == string.Empty)
            {
                psw1Label.Text = string.Empty;
            }
        }

        private void txtPassword_LostFocus(object sender, RoutedEventArgs e)
        {
            if (txtPassword.Password == string.Empty)
            {
                psw1Label.Text = "Password";
            }

            if (txtPassword.Password == string.Empty)
            {
                //txtPassword.Background = new SolidColorBrush(Colors.Red);
                validPassword = false;
                imgPass1Yes.Visibility = Visibility.Collapsed;
                imgPass1No.Visibility = Visibility.Visible;
                txbPasswordInfo.Text = "*Password can't be empty";
            }
            else
            {
                //txtPassword.Background = new SolidColorBrush(Colors.Green);
                validPassword = true;
                imgPass1Yes.Visibility = Visibility.Visible;
                imgPass1No.Visibility = Visibility.Collapsed;
                txbPasswordInfo.Text = string.Empty;
            }
        }

        private void txtPassword2_GotFocus(object sender, RoutedEventArgs e)
        {
            if (txtPassword2.Password == string.Empty)
            {
                psw2Label.Text = string.Empty;
            }
        }

        private void txtPassword2_LostFocus(object sender, RoutedEventArgs e)
        {
            if (txtPassword2.Password == string.Empty)
            {
                psw2Label.Text = "Confirm Password";
            }
            if (txtPassword2.Password == string.Empty)
            {
                //txtPassword2.Background = new SolidColorBrush(Colors.Red);
                validPassword2 = false;
                imgPass2Yes.Visibility = Visibility.Collapsed;
                imgPass2No.Visibility = Visibility.Visible;
                txbPassword2Info.Text = "*Please verify your password";
            }
            else if (txtPassword.Password != txtPassword2.Password)
            {
                //txtPassword2.Background = new SolidColorBrush(Colors.Red);
                validPassword2 = false;
                imgPass2Yes.Visibility = Visibility.Collapsed;
                imgPass2No.Visibility = Visibility.Visible;
                txbPassword2Info.Text = "*Passwords does not match";
            }
            else
            {
                //txtPassword2.Background = new SolidColorBrush(Colors.Green);
                validPassword2 = true;
                imgPass2Yes.Visibility = Visibility.Visible;
                imgPass2No.Visibility = Visibility.Collapsed;
                txbPassword2Info.Text = string.Empty;
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                txtPassword2.Focus();
            }
        }
        private void txtPassword2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Focus();
            }
        }

        private void txtOldPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                txtPassword.Focus();
            }
        }

        private void txtOldPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            if (txtOldPassword.Password == string.Empty)
            {
                oldpswLabel.Text = string.Empty;
            }
        }

        private void txtOldPassword_LostFocus(object sender, RoutedEventArgs e)
        {
            if (txtOldPassword.Password == string.Empty)
            {
                oldpswLabel.Text = "Old Password";
            }

            if (txtOldPassword.Password == string.Empty)
            {
                //txtPassword.Background = new SolidColorBrush(Colors.Red);
                validOldPassword = false;
                imgOldPassYes.Visibility = Visibility.Collapsed;
                imgOldPassNo.Visibility = Visibility.Visible;
                txbOldPasswordInfo.Text = "*Password can't be empty";
            }
            else
            {
                //txtPassword.Background = new SolidColorBrush(Colors.Green);
                validOldPassword = true;
                imgOldPassYes.Visibility = Visibility.Visible;
                imgOldPassNo.Visibility = Visibility.Collapsed;
                txbOldPasswordInfo.Text = string.Empty;
            }
        }

        private void grdChangeUserPicture_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            imgNewUserPicture.Opacity = .60;
            PhotoChooserTask newUserPhoto = new PhotoChooserTask();
            newUserPhoto.ShowCamera = true;
            newUserPhoto.Completed+=new EventHandler<PhotoResult>(newUserPhoto_Completed);
            newUserPhoto.Show();
        }

        private void newUserPhoto_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                App.OldUserImage = App.UserImage;
                // Create virtual store and file stream. Check for duplicate tempJPEG files.
                using (IsolatedStorageFile images = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (images.FileExists(userJPEG))
                    {
                        images.DeleteFile(userJPEG);
                    }

                    IsolatedStorageFileStream fileStream = images.CreateFile(userJPEG);

                    StreamResourceInfo sri = null;
                    Uri uri = new Uri(userJPEG, UriKind.Relative);
                    sri = Application.GetResourceStream(uri);

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.SetSource(e.ChosenPhoto);
                    WriteableBitmap wb = new WriteableBitmap(bitmap);

                    // Encode WriteableBitmap object to a JPEG stream.
                    Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

                    //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                    fileStream.Close();
                }

                BitmapImage setNewImg = new BitmapImage();
                setNewImg.SetSource(e.ChosenPhoto);
                this.imgNewUserPicture.Source = setNewImg;                
                newUserImage = setNewImg;                
                UserImageChanged = true;
                imgNewUserPicture.Opacity = 1;
            }
        
        }


        private void Cancel_Click(object sender, EventArgs e)
        {
            if (UserImageChanged == true)
            {
                App.UserImage = App.OldUserImage;
                UserImageChanged = false;
            }
            if (settings.Contains("HomeLocation"))
            {
                if (Convert.ToString(settings["HomeLocation"]) != oldUserHomeLocation) { UserHomeLocationChanged = true; }
                if (UserHomeLocationChanged == true)
                {
                    App.UserHomeLocation = oldUserHomeLocation;
                    settings["HomeLocation"] = App.UserHomeLocation;
                    settings.Save();
                    UserHomeLocationChanged = false;
                }
                NavigationService.Navigate(new Uri(App.PathMain, UriKind.Relative));
            }
        }
        private void Save_Click(object sender, EventArgs e)
        {
            if (UserImageChanged == true)
            {
                App.UserImage = newUserImage;
                MessageBox.Show("New changes saved!");
                UserImageChanged = false;                

            }
            if (settings.Contains("HomeLocation"))
            {
                if (Convert.ToString(settings["HomeLocation"]) != oldUserHomeLocation) { UserHomeLocationChanged = true; }
                if (UserHomeLocationChanged == true)
                {
                    App.UserHomeLocation = settings["HomeLocation"].ToString();
                    MessageBox.Show("New changes saved!");
                    UserHomeLocationChanged = false;
                }
            }
            NavigationService.Navigate(new Uri(App.PathMain, UriKind.Relative));
        }

        private void btnNewHomeLocation_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            oldUserHomeLocation = App.UserHomeLocation;
            if (App.popUpNewLocation == 0)
            {
                anyNews();                
                App.popUpNewLocation = 1;
                //trying to call the button
                Popup MessageBoxSaveHome;
                MessageBoxSaveHome = new Popup();
                MessageBoxSaveHome.IsOpen = true;
                MessageBoxSaveHome.Child = new MessageBoxSaveHome();
                MessageBoxSaveHome.HorizontalOffset = 0;
                MessageBoxSaveHome.VerticalOffset = -150;
                MessageBoxSaveHome.Closed += (s1, e1) =>
                { };
            }
        }

        private void chkLocationUpdate_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void PivotPages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PivotPages.SelectedItem == ProfileSettings)
            {
                anyNews();
            }
            if (PivotPages.SelectedItem == MapSettings)
            {
                //If there's a saved UserHomeLocation it will center the map to that Location.
                ///<! --- Home Location pin
                if (App.UserHomeLocation != string.Empty)
                {
                    //App.UserHomeLocation Lat and Long separation
                    string strFull = App.UserHomeLocation;
                    char[] strSeparator = new char[] { ',' };   // <-- Split on these
                    string[] strFullArray = strFull.Split(strSeparator, StringSplitOptions.RemoveEmptyEntries);
                    string strLat = string.Empty;
                    string strLon = string.Empty;
                    foreach (string entry in strFullArray)
                    {
                        if (strLat == string.Empty)
                        {
                            strLat = entry;
                        }
                        else
                        {
                            strLon = entry;
                        }
                    }
                    //Adding the pin with the separated coordinates now
                    Pushpin pinHome = new Pushpin();
                    pinHome.Location = new GeoCoordinate(Convert.ToDouble(strLat), Convert.ToDouble(strLon));//< -- Using separated strings here :D
                    map.Center = new GeoCoordinate(Convert.ToDouble(strLat), Convert.ToDouble(strLon));
                    map.ZoomLevel = 15;
                    anyNews();
                }
                else
                {
                    txbChangeUserHomeLocationDescription.Text = "No home location saved!";
                    btnNewHomeLocation.Content = "Set new home location";
                }
            }
        }
        

    }
}